package com.mintyfresh.tns.client;
import java.net.*;
import java.io.*;
import java.util.*;
import com.mintyfresh.tns.util.*;

public class ClientListener extends Thread {
	private static Socket socket = null;
	private String client;
	private static ObjectInputStream in;

	public ClientListener(Socket socket) {
		super("ClientListener");
		this.socket = socket;
	}

	/**
	 * run
	 * Receives Messages from the server.
	 * Receives a message from the server and passes it to the required method
	 * in the client. For simplicity sake, message names and method names
	 * should be the same.
	 */
	public void run() {
		try {
			in = new ObjectInputStream(socket.getInputStream());

			while(true) {
				Object o = in.readObject();
				if (!(o instanceof Message)) {
					System.err.println(
							"ERROR: OBJECT GIVEN TO CLIENT LISTENER NOT VALID");
					break;
				}
				Message msg = (Message)o;
				if (msg.type().equals("connected")) {
					Client.connected(msg);}
				else if (msg.type().equals("badUsername")) {
					Client.badUsername(msg);}
				else if (msg.type().equals("newRound")) {
					Client.newRound(msg);}
				else if (msg.type().equals("signalPlayerTurn")) {
					Client.signalPlayerTurn(msg);}
				else if (msg.type().equals("shotResults")) {
					Client.shotResults(msg);}
				else if (msg.type().equals("endRound")) {
					Client.endRound(msg);}
				else if (msg.type().equals("endGame")) {
					Client.endGame(msg);}
			} 
			in.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * kill
	 * command to stop the current thread
	 */
	public static void kill() {
		try {
			System.out.println("calling stop");
			in.close();
			socket.close();
			Thread.currentThread().interrupt();
		} catch (Exception e) {}
	}
}
